package com.imooc.order.controller.exceptions;

import com.imooc.order.utils.ResultVOUtil;
import com.imooc.order.vo.ResultVO;
import org.springframework.core.annotation.Order;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.Map;

/**
 * 目前不好使
 */
@ControllerAdvice
public class ExceptionsHandler {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    @Order(value = 1)
    public ResultVO<Map<String,String>> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex){

        System.out.println("handleMethodArgumentNotValidException");
        BindingResult bindingResult = ex.getBindingResult();
        String errorMesssage = "Invalid Request:";
        for (FieldError fieldError : bindingResult.getFieldErrors()) {
            errorMesssage += fieldError.getDefaultMessage() + ", ";
        }
        Map<String,String> map = new HashMap<>();
        map.put("errorMesssage",errorMesssage);
        return ResultVOUtil.error(map);

    }
}
